<!-- 账号管理 -->
<template>
<div class="dashboard-editor-container">
  <el-row style="background: #fff; padding: 16px;">
    <div style="display:flex;justify-content:space-between;">
        <div >
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
          <el-button type="warning" @click="DownloadFile2">模板下载</el-button>
        </div>
      </div>
    <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
      <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
      <el-table-column label="规则名称" prop="RuleName" align="left" show-overflow-tooltip></el-table-column>
      <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px" align="left">
        <template slot-scope="{row}">
          <span>{{ row.DeviceObj.length === 0 ? '全部' : row.DeviceObj.join(',') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测间隔" show-overflow-tooltip prop="Interval" width="160px" align="left"></el-table-column>
      <el-table-column label="规则生效" show-overflow-tooltip prop="IsValid" align="left">
        <template slot-scope="{row}">
          <span>{{ row.IsValid === 1 ? '生效' : '不生效' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" show-overflow-tooltip prop="Descp" align="left"></el-table-column>
      <el-table-column label="规则详情" show-overflow-tooltip prop="RuleDetail" align="left">
        <template slot-scope="scope">
          <span v-if="scope.row.screenTime > 0">进入屏保时间：{{scope.row.screenTime}}分钟；</span>
          <span v-if="scope.row.AutoCloseWall">开启墙纸定制；</span>
          <span v-if="scope.row.AutoCloseBack">开启锁屏背景；</span>
          <span v-if="scope.row.AutoCloseIcon">开启锁屏图标；</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="220">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button> -->
          <!-- :type="scope.row.IsValid ? 'info' : 'success'" -->
          <el-button size="mini" type="success" :disabled="scope.row.IsValid ? true : false" @click="disabledClick(scope.row,1)">启用</el-button>
          <el-button size="mini" type="info" :disabled="scope.row.IsValid ? false : true" @click="disabledClick(scope.row,0)">禁用</el-button>
          <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <el-dialog
    top="5vh"
    :close-on-click-modal="false"
    :close-on-press-escape=false
    :title="Action === 1 ? '添加规则' : '修改规则' "
    :visible.sync="dialogVisible"
    v-el-drag-dialog
    width="600px">
      <el-form label-width="130px" ref="accountForm" :model="accountForm" :rules="rules">
        <el-row >
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称:' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName"  :disabled="Action !== 1" :maxlength="300"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则生效:' prop="IsValid">
              <el-switch v-model="accountForm.IsValid" :active-value="1" :inactive-value="0" active-color="#3a8adb" inactive-color="#ccc"></el-switch>
            </el-form-item>
          </el-col> 
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='应用对象:' prop="DeviceObjType">
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="1">全部</el-radio>
              <!-- <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="2">指定校区</el-radio> -->
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="8">指定角色</el-radio>
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="6">指定资产</el-radio>
              <el-select v-model="accountForm.DeviceObj" style="width:100%" :placeholder="accountForm.DeviceObjType==1?'全部':'请选择'" multiple :disabled="accountForm.DeviceObjType === 1">
                <el-option
                  v-for="(item,index) in accountForm.DeviceObjType ===6 ?assetList:DeviceObjList"
                  :key="index"
                  :label="item.DeviceName"
                  :value="item.DeviceName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="备注信息" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" :rows="3"  v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='检测间隔:' prop="Interval">
              <el-input v-model="accountForm.Interval"  oninput="value=value.replace(/[^0-9]/g,'')"  maxlength="9"><span slot="append">秒钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='进入屏保:' prop="screenTime">
              <el-input v-model="accountForm.screenTime"  oninput="value=value.replace(/[^0-9]/g,'')"  maxlength="9"><span slot="append">分钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （0表示不启用）
            </span>
          </el-col>
          <el-col :xs="10" :sm="10" :lg="10">
            <el-form-item label='' prop="" label-width="60px">
              <el-checkbox v-model="accountForm.AutoCloseWall" :true-label="1" :false-label="0">开启终端电脑桌面墙纸定制</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="10" :sm="10" :lg="10">
            <el-form-item label='' prop="AutoCloseBack" label-width="60px">
              <el-checkbox v-model="accountForm.AutoCloseBack" :true-label="1" :false-label="0">开启终端电脑锁屏背景定制</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="10" :sm="10" :lg="10">
            <el-form-item label='' prop="AutoCloseIcon" label-width="60px">
              <el-checkbox v-model="accountForm.AutoCloseIcon" :true-label="1" :false-label="0">开启终端电脑锁屏图标定制</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='上传文件:'>
              <el-upload
                class="upload-demo"
                action="#" 
                multiple
                ref="upload"
                :accept="'.zip'"
                :on-change="filechange"
                :http-request="uploadFile"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :before-upload="beforeAvatarUpload"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary" >点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
import { connrequest,uploadfile } from '@/api/firstPage'
import { getToken } from '@/utils/auth' // get token from cookie
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
directives: { elDragDialog },
data() {
return {
  pageNum: 1,
  pageSize: 10,
  tableData: [],
  RoleList: [],
  fileList: [],
  Attach: [],
  Action: 1,
  dialogVisible: false,
  controlUpload:true,
  accountForm: {},
  DeviceObjList: [],
  assetList: [],
  rules: {
    RuleName: [
      { required: true, message: "请输入规则名称"}
    ],
  }
}
},
//生命周期 - 创建完成（访问当前this实例）
created() {
  this.getData()
  this.CenterGetDevice()
},
//生命周期 - 挂载完成（访问DOM元素）
mounted() {

},
methods: {
  async getData(){
    const res = await connrequest('GetDesktopCustomRule')
    this.tableData = res.Data
  },
  async CenterGetDevice(){
    const data = {
      Paging:{
        QueryPageNo: 1,
        QueryPageLength: 100000000
      },
      Filter:{
        Status: 0,
      }
    }
    const res = await connrequest('CenterGetDevice', data)
    this.assetList = res.Data
  },
  async DeviceObjTypeChange(value){
    this.$set(this.accountForm, 'DeviceObj', '')
    if(value === 1){
      this.DeviceObjList = []
    }else if(value === 2){
      const res = await this.GetSchoolStatusSumTree()
      this.DeviceObjList = [res]
    }else if(value === 8){
      const res = await this.GetRolestatus()
      var arr = []
      res.map(item => {
        var val ={'DeviceName': item.Role}
        arr.push(val)
      })
      this.DeviceObjList = arr
    }else{
      const res = await this.GetDeviceStatusSumTree()
      this.DeviceObjList = [res]
    }
  },
  // 获取校区树
  async GetSchoolStatusSumTree() {
    const res = await connrequest('GetSchoolStatusSumTree')
    return this.transformData(res.Data)
  },
  // 获取角色
  async GetRolestatus() {
    const res = await connrequest('GetParamDictRole')
    return res.Data
  },
  // 获取资产树
  async GetDeviceStatusSumTree() {
    const res = await connrequest('GetDeviceStatusSumTree')
    return this.transformData(res.Data)
  },
  transformData(inputData) {
    const { RootName, PrimArea} = inputData;
      return {
        SubClass: RootName,
        value: RootName,
        level: 1,
        children: PrimArea.map(area => ({
          SubClass: area.PrimAreaName,
          value: area.PrimAreaName,
          level: 2,
          children: area.SecondArea.map(secondArea => ({
            SubClass: secondArea.SecondAreaName,
            value: secondArea.SecondAreaName,
            level: 3,
        }))
      }))
    }
  },
  // 获取子节点的校区
  async lazyLoad(node, resolve){
    if(node.level < 3){
      resolve(node.data) 
    }else{
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
        Filter:{
          SecondArea: node.label,
        }
      }
      const res = await connrequest('GetSchool', data)
      let arr = []
      res.Data.map(item => {
        arr.push( {SubClass: item.SchoolName, value: item.SchoolName, level: 4, children: undefined} )
      })
      resolve(arr) 
    }
  },
  // 获取子节点的资产
  async lazyLoad2(node, resolve){
    if(node.level < 3){
      resolve(node.data) 
    }else{
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
        Filter:{
          SecondArea: node.label,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      let arr = []
      res.Data.map(item => {
        arr.push( {SubClass: item.DeviceName, value: item.DeviceName, level: 4, children: undefined} )
      })
      resolve(arr) 
    }
  },
  addClick(){
    this.Action = 1
    this.fileList = []
    this.Attach = []
    this.dialogVisible = true
    this.$nextTick(()=>{
      if (this.$refs['accountForm']) {
        this.accountForm = {
          IsValid: 1,
          DeviceObjType: 1,
          Interval: 0,
          screenTime:0,
          AutoCloseWall:0,
          AutoCloseBack:0,
          AutoCloseIcon:0,
          DeviceObj:[],

        }
      }
      this.$refs['accountForm'].resetFields();
    })
  },
  handleChange(row){
  },
  changeClick(row, index){
    this.fileList = []
    const detailfile ={}
    detailfile.name = row.OrigFileName
    detailfile.uid  = row.ResFileName
    this.Action = 2
    this.fileList.push(detailfile)
    let arr = []
    this.fileList.map(item => {
      arr.push({OrigFileName: item.name, ResFileName: item.uid + ''})
    })
    this.Attach = arr
    this.$nextTick(()=>{
      this.accountForm = {...row}
      this.$refs['accountForm'].resetFields();
    })
    this.dialogVisible = true
  },
  async disabledClick(row,isValid){
    var info = {...row}
    info.IsValid = isValid
    // row.IsValid = isValid
    let data = {
        Data: {
          Action: 2,
          Detail: {
            ...info
          }
        }
      }
      const res = await connrequest('EditDesktopCustomRule', data)
      if(res.Status.StatusCode === 0){
        this.$message({
          type: 'success',
          message: isValid ? '启用成功' : '禁用成功'
        });
        this.getData()
        this.dialogVisible = false
      }
  },
  deleteClick(row){
    this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let data = {
        Data: {
          Action: 3,
          Detail: {...row}
        }
      }
      const res = await connrequest('EditDesktopCustomRule', data)
      if(res.Status.StatusCode === 0){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getData()
        this.dialogVisible = false
      }
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });          
    });
  },
  submit(){
    if(this.Attach.length !== 1){
        this.$message.error('请上传文件')
        return false
      }
    this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          if(this.accountForm.DeviceObjType === 2){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择校区')
            return false
          }
        }
        if(this.accountForm.DeviceObjType === 8){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择角色')
            return false
          }
        }
        if(this.accountForm.DeviceObjType === 6){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择资产')
            return false
          }
        }
        // if(this.accountForm.DeviceObj.length>0)
        // {
        //   var  info = this.accountForm.DeviceObj
        //   this.accountForm.DeviceObj = [info]
        // }
        let data = {
          Data: {
            Action: this.Action,
            Detail: { 
              ...this.accountForm,
              FileSize: this.FileSize,
              OrigFileName: this.Attach[0]?.OrigFileName,
              ResFileName: this.Attach[0]?.ResFileName,
              // CreateTime: Date.now()
            }
          }
        }
        const res = await connrequest('EditDesktopCustomRule', data)
        if(res.Status.StatusCode === 0){
          this.getData()
          this.dialogVisible = false
        }
      }
    })
  },
  filechange(file, fileList){
      let arr = []
      fileList.map(item => {
        arr.push({OrigFileName: item.name, ResFileName: item.uid + ''})
      })
      this.Attach = arr
    },
    async uploadFile(file){
      console.log(file.file);
      let formData = new FormData();
      formData.append('CmdCode', "UploadDesktopAttach");
      formData.append('OrigFileName', file.file.name);
      formData.append('ResFileName', file.file.uid);
      formData.append('file', file.file);
      formData.append('Token', getToken());
      const res = await uploadfile('UploadDesktopAttach',formData)
      if(res.Status.StatusCode === 0) {
        this.FileSize = file.file.size
        this.$message.success('文件上传成功')
      }
    },
    handlePreview(){},
    async handleRemove(file, fileList) {
      if(this.controlUpload)
      {
        const data = {
          Data:{
            ResFileName: file.uid
          }
        }
        const res = await connrequest('DeleteDesktopAttach', data)
        if(res.Status.StatusCode === 0){
          this.Attach = this.Attach.filter(item => item.uid !== file.uid);
          this.Attach = this.Attach.filter(item => item.ResFileName != file.uid);
          this.FileSize = 0
          this.$message.success('文件删除成功')
        }
      }
      
    },
    beforeRemove(file, fileList) {
      if(this.controlUpload)
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeAvatarUpload(file) {
        const typeArry = ['.zip', '.ZIP'];
        const type = file.name.substring(file.name.lastIndexOf('.'));
        const isTar = typeArry.indexOf(type) > -1;
        if (!isTar) {
          this.controlUpload = false
          this.$message.error('上传文件只能是 zip 格式!');
          return false
        }
        else
          this.controlUpload = true
        return true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    async DownloadFile2(){
      let softwareName =  '企业形象模板.zip'
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = softwareName;
      a.click();
      a.remove();
    },
}
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.el-dialog__title::before {
  padding-left: 30px; /* 调整标题和图标的距离 */
  background-image: url('../../assets/logo.png'); /* 指定图标路径 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
  background-position: left center; /* 将图标放在标题左侧中间 */
}

</style>